package com.llz.leaveApply.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.llz.leaveApply.dto.Result;
import com.llz.leaveApply.entity.User;
import com.llz.leaveApply.service.IUserService;
import com.llz.leaveApply.utils.MD5Util;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    IUserService userService;
    private static final String USER_NAMEPREFIX = "user_";

    @PostMapping("/register")
    public Result regiser(@RequestParam String userNumber, @RequestParam String password) {
//        System.out.println(user);

        if (userService.query().eq("user_number", userNumber).count() > 0) {

            return Result.fail("该学号已被注册");
        }
        //数据库没相同的用户名直接保存
        User user = new User();
        user.setUserNumber(userNumber);
        user.setPassword(MD5Util.encode(password));
        //随机一个名字
        user.setName(USER_NAMEPREFIX + RandomUtil.randomString(10));
        if (userService.save(user)) {
            return Result.ok("注册成功");
        } else {
            return Result.fail("注册失败");
        }

    }

    @PostMapping("/login")
    public Result login(@RequestParam("userNumber") String userNumber, @RequestParam("password") String password) {
//        Object usrInData = null;
//        (User) userService.query().eq("name", user.getName()).setEntity(User usrInData);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_number", userNumber);
        User userInData = userService.getOne(queryWrapper);
        if (userInData == null) {
            return Result.fail("用户不存在");
        }
//        将传入的密码转成密文
        String passwordEncode=MD5Util.encode(password);
//        将数据库的密文密码取出
        if (userInData.getPassword().equals(passwordEncode)) {
            Map resMap = new HashMap<>();
            resMap.put("user", userInData);
            return Result.ok(resMap);
        }
        return Result.fail("密码错误");
    }


    /**
     * 获得指定userNumber 的审批人员 <id,姓名>表
     */

    @PostMapping("approvers")
    public Result getApprover(@RequestParam("userNumber") String userNumber) {
       User user= userService.query().eq("user_number", userNumber).one();
//
       String approverStr= user.getApprovers();
        List<User> approvers=null;

       if(approverStr!=null||approverStr!=""){
           String [] idList= approverStr.split(",");
//           这段就相当于 select id,name from user where id in (....,....)
           approvers= (List<User>) userService.query().select("id","name").in("id",idList).list();
       }
        return Result.ok(approvers);
    }


    @GetMapping("/test")
    Result Test() {
        return Result.ok("成功");
    }
}
